<template>
    <div class="container">
        <el-form ref="form" :model="form" label-width="100px" size="mini" v-loading="showLoading">
            <el-form-item label="表格名称">
                <el-input v-model="form.bgmc"></el-input>
            </el-form-item>
            <el-form-item label="内容描述">
                <el-input type="textarea" v-model="form.nrms" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
            </el-form-item>
            <el-form-item label="截止日期">
                <el-date-picker v-model="form.tbjzrq" type="date" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="表格附件">
                <div class="uploadBox">
                    <span style="margin-right:20px;" v-if="fileName!=''">{{fileName}}</span>
                    <el-upload class="upload-demo" ref="upload" :before-upload="beforeUpload" action :show-file-list="false" :http-request="httpRequest" :multiple="false" accept=".xls,.csv,.xlsx">
                        <el-button size="mini" type="primary">导入</el-button>
                    </el-upload>
                    <el-button v-if="fileName!=''" size="mini" type="primary" @click="delFile()" style="margin-left:10px;">删除</el-button>
                </div>

            </el-form-item>
            <el-form-item label="下发对象">
                <div>
                    <el-button size="mini" type="primary" @click="getqueryXfdx()">默认对象</el-button>
                </div>
                <div class="btnC">
                    <el-button type="danger" size="mini" class="mybtn" @click="delxfdx()"><i class="el-icon-minus"></i></el-button>
                    <el-button type="danger" size="mini" class="mybtn" @click="addxfdx()"><i class="el-icon-plus"></i></el-button>
                </div>
                <el-table v-loading="loading" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center">
                    </el-table-column>
                    <el-table-column prop="swjgdm" label="接收单位" align="center">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.swjgdm" @change="handleJsrdwChange(scope.row,scope.$index)">
                                <el-option v-for="item in jsdwOption" :key="item.swjgdm" :label="item.jsdwmc" :value="item.swjgdm"> </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="userId" label="接收人" align="center">
                        <template slot-scope="scope">

                            <el-select v-model="scope.row.userId" @change="handleJsrChange(scope.row)">
                                <el-option v-for="item in scope.row.jsrOption" :key="item.userId" :label="item.jsr" :value="item.userId"> </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tbzt" label="填报信息" align="center">
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="创建时间">
                        <el-input v-model="form.cjrq" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="创建人">
                        <el-input v-model="form.cjr" disabled></el-input>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-form-item>
                <div style="text-align:center;">
                    <el-button type="primary" @click="onSubmit('')">保存</el-button>
                    <el-button type="primary" @click="onSubmit(1)">下发</el-button>
                    <el-button @click="go('list')">返回</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
// require component
import { queryXfdx, querySwjg, querySwry, add, queryById } from '@/api/zcgj/gxbg'

export default {

    props: {
        id: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            loading: false,
            form: {
                bgmc: '',
                nrms: '',
                tbjzrq: '',
                xfdxList: '',
                cjrq: '',
                cjr: '',


            },
            file: '',
            fileName: '',
            jsdwOption: [],
            jsrOption: [],
            tableData: [
                // { swjgdm: '', jsdwmc: '', userId: '', jsr: '', tbzt: '未填报', jsrOption: [] }
            ],
            docSelect: [],
            showLoading: false
        }
    },
    mounted() {
        this.getById()
    },
    methods: {
        getById() {
            this.showLoading = true
            this.tableData = []
            queryById({ id: this.id }).then(res => {
                this.getquerySwjg()
                console.log(res)
                this.form = res.data.gxbgSjsc
                this.fileName = res.data.gxbgSjsc.wjmc
                let xfdxList = res.data.xfdxList
                for (let i = 0; i < xfdxList.length; i++) {
                    this.tableData.push({ ...xfdxList[i], tindex: '', jsrOption: [] })
                    querySwry({ swjgdm: xfdxList[i].swjgdm }).then(res => {
                        this.showLoading = false
                        if (res.code == 200) {

                            this.tableData[i].jsrOption = res.data
                        }
                        this.loading = false
                    })
                }

            })
        },
        onSubmit(flag) {
            if (this.form.bgmc == '') {
                this.$message.error('表格名称不能为空')
                return false
            }
            if (this.form.nrms == '') {
                this.$message.error('内容描述不能为空')
                return false
            }
            if (this.form.tbjzrq == '') {
                this.$message.error('填报截止日期不能为空')
                return false
            }
            if (this.fileName == '') {
                this.$message.error('请上传表格附件')
                return false
            }
            if (this.tableData.length <= 0) {
                this.$message.error('下发对象不能为空')
                return false
            }
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].jsdwmc == '') {
                    this.$message.error('接收单位不能为空')
                    return false
                } else if (this.tableData[i].jsr == '') {
                    this.$message.error('接收人不能为空')
                    return false
                }
            }

            let fd = new FormData();
            if (this.form.bgfj != '') {
                fd.append('file', null)
            } else {
                fd.append('file', this.file.file)
            }


            let param = {
                ...this.form,
                xfdxList: this.tableData
            }
            fd.append('json', JSON.stringify(param))
            fd.append('flag', flag)
            fd.append('id', this.form.id)

            this.showLoading = true
            add(fd).then(res => {
                this.showLoading = false
                if (res.code == 200) {
                    if (flag == '1') {
                        this.$message.success('下发成功')
                    } else {
                        this.$message.success('保存成功')
                    }
                    this.go('list')
                }
            })
        },
        // submitUpload() {
        //     this.$refs.upload.submit();
        // },
        beforeUpload(file, fileList) {
            if (file.size > 1024 * 1024 * 10) {
                this.$message.warning(
                    "你上传的 \“" + file.name + "\” 文件过大，请上传小于2M的文件。"
                );
                return false;
            }

            if (
                file.name.indexOf("@") != -1 ||
                file.name.indexOf("#") != -1 ||
                file.name.indexOf('""') != -1 ||
                file.name.indexOf("<") != -1 ||
                file.name.indexOf(">") != -1 ||
                file.name.indexOf("?") != -1 ||
                file.name.indexOf("|") != -1 ||
                file.name.indexOf("/") != -1 ||
                file.name.indexOf(":") != -1 ||
                file.name.indexOf("`\`") != -1
            ) {
                this.$message.warning(
                    "你上传的 \“" +
                    file.name +
                    "\” 文件有特殊字符，文件名中不可存在特殊字符,请重新上传"
                );
                return false;
            }

            let index = file.name.lastIndexOf(".");
            let Type = file.name.substr(index + 1, file.name.length);
            if (["xls", "csv", "xlsx"].indexOf(Type.toLowerCase()) === -1) {
                this.$message({
                    type: "warning",
                    message: "请上传后缀名为xls,csv,xlsx的附件！",
                });
                return false;
            }
        },
        httpRequest(data) {
            console.log(data)
            this.fileName = data.file.name
            this.file = data

        },
        delFile() {
            this.fileName = ''
            this.file = ''
        },
        


        getquerySwjg() {
            querySwjg().then(res => {
                if (res.code == 200) {
                    console.log(res)
                    this.jsdwOption = res.data
                }
            })
        },
        handleJsrdwChange(row, index) {
            console.log(row)
            row.tindex = index
            for (let i = 0; i < this.jsdwOption.length; i++) {
                if (row.swjgdm == this.jsdwOption[i].swjgdm) {
                    row.jsdwmc = this.jsdwOption[i].jsdwmc
                }
                row.userId = ''
            }
            querySwry({ swjgdm: row.swjgdm }).then(res => {
                if (res.code == 200) {
                    row.jsrOption = res.data
                }
            })
            console.log(row)
        },
        handleJsrChange(row) {

            for (let i = 0; i < row.jsrOption.length; i++) {
                if (row.userId == row.jsrOption[i].userId) {
                    row.jsr = row.jsrOption[i].jsr
                }
            }
        },
        addxfdx() {
            this.loading = true
            let param = { tindex: '', swjgdm: '', jsdwmc: '', userId: '', jsr: '', tbzt: '未填报', jsrOption: [] }
            this.tableData.push(param)
            this.loading = false
        },
        delxfdx() {
            if (this.docSelect.length > 0) {
                this.$confirm('该删除后将不可恢复，是否删除？', '友情提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'JmconfirmCancelButton',
                    type: 'warning'
                }).then(() => {
                    for (let i = 0; i < this.docSelect.length; i++) {
                        this.tableData.splice(this.docSelect[i].tindex, 1)
                    }

                })

            } else {
                this.$message.error('请选择一条数据删除');
                return false;
            }
        },
        getqueryXfdx() {
            this.tableData = []
            this.loading = true
            queryXfdx().then(res => {

                if (res.code == 200) {
                    for (let i = 0; i < res.data.length; i++) {
                        this.tableData.push({ ...res.data[i], tindex: '', tbzt: '未填报', jsrOption: [] })
                        querySwry({ swjgdm: res.data[i].swjgdm }).then(res => {
                            if (res.code == 200) {

                                this.tableData[i].jsrOption = res.data
                            }
                            this.loading = false
                        })
                    }

                }

            })
        },
        handleSelectionChange(rows) {
            console.log(rows)
            this.docSelect = rows
        },
        //获取模型指标option
        //待处理
        go(name, params) {
            this.$emit('changePage', name, params);
        },
    }
}
</script>

<style lang="scss" scoped>
.container {
    height: 100%;
    width: 100%;
    background-color: #fff;
    padding: 15px 50px;

    .btn {
        padding: 8px 8px 8px 0;
    }
    .btnC {
        text-align: right;
        margin-bottom: 2px;

        .mybtn {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            padding: 0;
        }
    }
    .el-select,
    .el-input,
    .el-date-editor {
        width: 100%;
    }

    .imgIcon {
        width: 30px;
        height: 30px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .codeC {
        display: flex;
        justify-content: space-between;

        .tabs {
            width: 35px;

            .tabs-item {
                text-align: center;
                padding: 11px;
                height: 80px;
                background-color: rgba(22, 155, 213, 1);
                box-sizing: border-box;

                border-radius: 5px;
                -moz-box-shadow: none;
                -webkit-box-shadow: none;
                box-shadow: none;
                font-size: 14px;
                color: #ffffff;
                border-radius: 5px;
            }
        }
    }

    .uploadBox {
        display: flex;
        justify-self: start;
    }
}
</style>